<template>
  <div class="site-wrapper">
    <div class="header clearfix">
      <el-button size="small" type="primary" v-if="emailType !== 'hsz' && emailType !== 'ljyj'" @click="openEmailDialog">写邮件</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType !== 'hsz' && emailType !== 'cgx' && emailType !== 'ljyj' && emailType !== 'yfs' && emailType !== 'ds'" @click="dealEmail(false)">设置已处理</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType !== 'hsz' && emailType !== 'cgx' && emailType !== 'ljyj' && emailType !== 'yfs' && emailType !== 'ds'" @click="redealEmail(false)">设置未处理</el-button>
      <el-button size="small" type="primary" v-if="emailType === 'sjx' && emailType !== 'ds'" @click="refreshEmail">刷新邮箱</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType !== 'hsz' && emailType !== 'cgx' && folderId !== '-1' && emailType !== 'ds'" @click="openMoveDialog">移动邮件</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType !== 'hsz' && emailType !== 'ds' && emailType !== 'dcl'" @click="delEmail(false)">删除</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType === 'ds'" @click="delDsTask(false)">删除</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType === 'hsz'" @click="forceDelEmail(false)">彻底删除</el-button>
      <el-button size="small" :disabled="multipleSelection.length === 0" type="primary" v-if="emailType === 'hsz'" @click="rebackEmail(false)">还原邮件</el-button>
      <div class="filter" @click="showFilter = true;"><img src="../../../../assets/livolobim/filter.png" alt="">搜索</div>
      <div class="mask" v-if="showFilter" @click="showFilter = false;"></div>
      <div class="filter-wrapper" v-if="showFilter && emailType !== 'ds'">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="filterData" style="padding: 0 16px;" label-width="110px">
          <el-form-item label="发送时间范围">
            <el-date-picker
              style="width: 100%;"
              v-model="timeRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="发件人">
            <el-input v-model="filterData.addressor"></el-input>
          </el-form-item>
          <el-form-item label="收件人">
            <el-input v-model="filterData.receive"></el-input>
          </el-form-item>
          <el-form-item v-if="emailType !== 'cgx' && emailType !== 'ljyj' && emailType !== 'hsz' && emailType !== 'yfs' && emailType !== 'dcl'" label="处理状态">
            <el-select v-model="filterData.isDeal" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in dealArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="searchItem(true)">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetFilter">重置</el-button>
        </div>
      </div>
      <div class="filter-wrapper" v-if="showFilter && emailType === 'ds'">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="filterData2" style="padding: 0 16px;" label-width="110px">
          <el-form-item label="邮件主题">
            <el-input v-model="filterData2.subject"></el-input>
          </el-form-item>
          <el-form-item  label="发送类型">
            <el-select v-model="filterData2.sendType" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in sendTypeArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="发送结果">
            <el-select v-model="filterData2.sendResult" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in sendResultArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="发送状态">
            <el-select v-model="filterData2.hasSent" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in hasSentArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="searchTimeItem(true)">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetTimeFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <el-table :height="tableHeight" @row-click="getEmailDetail" :highlight-current-row="true" @selection-change="handleSelectionChange" :data="tableData" border style="width: 100%">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column v-if="emailType === 'sjx' || emailType === 'ljyj' || emailType === 'dcl'" align="center" :show-overflow-tooltip="true" prop="addressor" label="发送人" min-width="100"></el-table-column>
        <el-table-column v-if="emailType !== 'sjx' && emailType !== 'ljyj' && emailType !== 'dcl'" align="center" :show-overflow-tooltip="true" prop="receive" label="收件人" min-width="100"></el-table-column>
        <el-table-column align="center" :show-overflow-tooltip="true" prop="subject" label="主题" min-width="120"></el-table-column>
        <el-table-column align="center" v-if="emailType !== 'ds'" :show-overflow-tooltip="true" prop="customerName" label="相关客户" min-width="100">
          <template slot-scope="scope">
            <span v-for="(item,idx) in scope.row.customerName.split(',')" :key="item.id" @click="goKH(scope.row.customerId,idx, item)" style="cursor:pointer;color:#409EFF;">
              {{item}} {{(idx + 1) === scope.row.customerName.split(',').length? '': ','}}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="emailType === 'ds'" label="发送日期" width="170">
          <template slot-scope="scope">
            {{scope.row.sendTime}} {{scope.row.sendTimeDetail}}
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="emailType === 'ds'" prop="sendDate" label="发送类型" width="130">
          <template slot-scope="scope">
            {{scope.row.sendType === 1? '普通发送': '一对一发送'}}
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="emailType === 'ds'" prop="sendDate" label="发送状态" width="130">
          <template slot-scope="scope">
            {{scope.row.hasSent? '已发送': '未发送'}}
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="emailType === 'ds'" prop="sendDate" label="发送结果" width="130">
          <template slot-scope="scope">
            {{scope.row.sendResult === ''? '暂无': scope.row.sendResult === true? '发送成功': '发送失败'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="emailType === 'ds'" width="120" align="center">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.hasSent" @click="editTask(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="delDsTask(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="emailType !== 'ds'" prop="sendDate" label="日期" width="100"></el-table-column>
        <el-table-column align="center" v-if="emailType !== 'ds'" :show-overflow-tooltip="true" prop="account" label="账号" min-width="100"></el-table-column>
        <el-table-column align="center" v-if="emailType !== 'ds' && emailType !== 'yfs' && emailType !== 'cgx' && emailType !== 'hsz' && emailType !== 'ljyj'" prop="isDeal" label="状态" width="100">
          <template slot-scope="scope">
            {{scope.row.isDeal? '已处理': '未处理'}}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[15, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog width="1000px" :visible.sync="showEmailInit" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">请先填写邮箱信息</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form ref="form" :model="emailForm" label-width="140px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="用户名：">
                  <span slot="label">邮箱账号<span style="color: red;">*</span>：</span>
                  <el-input v-model="emailForm.account"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="登录密码/授权码：">
                  <span slot="label">登录密码/授权码<span style="color: red;">*</span>：</span>
                  <el-input v-model="emailForm.password"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="邮箱昵称：">
                  <span slot="label">邮箱昵称<span style="color: red;">*</span>：</span>
                  <el-input v-model="emailForm.nickname"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showEmailInit = false">关闭</el-button>
              <el-button style="float:right;margin-right: 10px;" size="small" type="primary" @click="initEmail">创建</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <div class="email-wrapper">
      <div class="email-detail" v-if="emailDetail.id" ref="iframewrapper">
        <div class="email-header">
          <p class="title">{{emailDetail.subject}}</p>
          <p v-if="emailType !== 'ds'">发件人: {{emailDetail.addressor}}</p>
          <p>日期: {{emailType !== 'ds' ? emailDetail.sendDate: emailDetail.sendTime + ' ' + emailDetail.sendTimeDetail}}</p>
          <p>收件人: {{emailDetail.receive}}</p>
          <p>抄送人: {{emailDetail.cc}}</p>
          <div class="email-btns">
            <el-button v-if="emailType === 'yfs'" size="mini" type="primary" @click="reply('zcbj')">再次编辑发送</el-button>
            <el-button v-if="emailType !== 'cgx' && emailType !== 'ds'" size="mini" type="primary" @click="reply('hf')">回复</el-button>
            <el-button v-if="emailType !== 'cgx' && emailType !== 'ds'" size="mini" type="primary" @click="reply('qbhf')">全部回复</el-button>
            <el-button v-if="emailType !== 'cgx' && emailType !== 'ds'" size="mini" type="primary" @click="reply('zf')">转发</el-button>
            <el-button v-if="emailType === 'cgx'" size="mini" type="primary" @click="reply('cg')">编辑</el-button>
            <el-button v-if=" emailType === 'ds' && !emailDetail.hasSent" size="mini" type="primary" @click="editTask(emailDetail)">编辑</el-button>
            <el-button v-if="emailType === 'cgx' && emailType !== 'ds'" size="mini" type="primary" @click="sendEmail">发送</el-button>
            <el-button v-if="emailType !== 'ds'" size="mini" type="primary" @click="delEmail(emailDetail.messageUid)">删除</el-button>
            <el-button v-if="emailType === 'ds'" size="mini" type="primary" @click="delDsTask(emailDetail.id)">删除</el-button>
          </div>
        </div>
        <div class="cutline"></div>
        <div class="email-content">
          <iframe ref="emailiframe" :srcdoc="emailDetail.content" frameborder="0" allowtransparency="true" scrolling="no" style="width: 100%;"></iframe>
        </div>
        <div class="email-file" v-if="emailDetail.fileList.length > 0">
          <div style="width: 60px;">附件：</div>
          <div class="email-file-wrapper">
            <div class="file" v-for="(file) in emailDetail.fileList" :key="file.id">
              <div class="file-type"><img :src="getPic(file.fileName)" alt=""></div>
              <div class="file-info">
                <p>{{file.fileName}}</p>
                <p>{{file.size / 1000}}KB</p>
                <div class="file-action">
                  <el-tooltip effect="light" content="预览" placement="bottom">
                    <i class="el-icon-view" v-if="canPreview(file.fileName)" @click="previewPic(file.fileUrl)"></i>
                  </el-tooltip>
                  <el-tooltip effect="light" content="下载" placement="bottom">
                    <i class="el-icon-download" @click="downloadFile(file.fileUrl, file.fileName)"></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="emial-empty" v-if="!emailDetail.id">未选择邮件</div> 
    </div> 
    <el-dialog title="移动邮件" :visible.sync="moveDialogVisible" :append-to-body="true" width="500px">
      <el-row :gutter="20">
        <el-col :span="6" style="padding-top: 10px;text-align:right;">
          <div class="grid-content bg-purple">
            <i class="el-icon-connection"></i>
            移动到
          </div>
        </el-col>
        <el-col :span="16">
          <el-select ref="labelSelected" v-model="moveForm.targetFolderId" placeholder="点击选择" style="width:300px">
            <el-option v-for="value in moveToList" :key="value.id" :label="value.sysFolderName" :value="value.id" style="width:300px"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="moveEmail">移动</el-button>
      </div>
    </el-dialog>
    <Email ref="email" :emailType="emailType"/>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'
import Email from './Email.vue'
import {Loading, Message} from 'element-ui'

export default {
  data() {
    return {
      moveDialogVisible: false,
      timeRange: ['', ''],
      filterData: {
        receive: ''
      },
      showEmailInit: false,
      showFilter: false,
      loading:false,
      showForm: false,
      tableHeight: window.tableHeight,
      tableData: [],
      page:1,
      pageSize: 15,
      totalPage: 1,
      custormerList: [],
      filterData: {
        receive: '',
        addressor: '',
        isDeal: ''
      },
      filterData2: {
        sendType: '',
        sendResult: '',
        hasSent: '',
        subject: ''
      },
      dealArr: [
        {
          name: '已处理',
          id: true
        },
        {
          name: '未处理',
          id: false
        }
      ],
      sendTypeArr: [
        {
          name: '普通发送',
          id: 1
        },
        {
          name: '一对一发送',
          id: 2
        }
      ],
      sendResultArr: [
        {
          name: '发送成功',
          id: true
        },
        {
          name: '发送失败',
          id: false
        }
      ],
      hasSentArr: [
        {
          name: '已发送',
          id: true
        },
        {
          name: '未发送',
          id: false
        }
      ],
      emailForm: {
        account: '',
        password: '',
        nickname: ''
      },
      folderId: '',
      emailDetail: {},
      emailType: '',
      custormerList: [],
      multipleSelection: [],
      moveToList: [],
      moveForm: {
        sourceFolderId: '',
        targetFolderId: '',
        uids: ''
      }
    }
  },
  components: {
    Email
  },
  mixins: [dingMixin],
  async mounted() {
    this.$nextTick(() => {
      this.tableHeight = (document.documentElement['clientHeight'] - 200) / 2;
    })
    window.onresize = () => {
      this.tableHeight = (document.documentElement['clientHeight'] - 200) / 2;
    }
    this.folderId = window.FOLDERID;
    this.emailType = window.EMAILTYPE;
    this.getListData(true)
  },
  methods: {
    goKH(idsStr, idx, name){
      let ids = idsStr.split(',');
      let target = ids[idx];
      this.$parent.currentNavIndex = 0;
      window.CURRENTCUSTOMERID = target;
      window.CURRENTCUSTOMERNAME = name;

      this.$parent.currentMenu = {
        name: '全部客户',
        icon: 'qbkh',
        url: 'qbkh'
      };
      this.$router.push({ name: 'lcrm-qbkh'})
    },
    async reply(type) {
      let copyEmail = formUtil.deepCopy(this.emailDetail);
      if(!copyEmail.content) {
        if(copyEmail.contentUrl) {
          let result = await this.fetchEmailContent(copyEmail.contentUrl)
          copyEmail.content = result;
        }else {
          copyEmail.content = ''
        }
      }
      if(type !== 'cg' && type !== 'zcbj') {
        let replyStr = `
          <div></div><br><div></div><br><div></div><br><div></div>
          <div style="font-size:12.0px;font-family:Arial Narrow;padding:2.0px 0 2.0px 0;">---------------------------------------------------------------------------------------------------------------</div>
          <div style="clear:both;">Subject：${this.emailDetail.subject}</div>
          <div style="clear:both;">From: ${this.emailDetail.addressor}</div>
          <div style="clear:both;">Date: ${this.emailDetail.sendDate}</div>
          <div style="clear:both;">To: ${this.emailDetail.receive}</div>
        `
        if((type === 'hf' || type === 'qbhf') && copyEmail.subject.indexOf('Re：') !== 0) copyEmail.subject = 'Re：' + copyEmail.subject;
        if(type === 'zf' && copyEmail.subject.indexOf('Forward：') !== 0) copyEmail.subject = 'Forward：' + copyEmail.subject;
        
        copyEmail.content = replyStr + copyEmail.content;
      }
      this.$refs.email.openEmail(copyEmail, type);
    },
    async editTask(email) {
      let copyEmail = formUtil.deepCopy(email);
      if(!copyEmail.content) {
        if(copyEmail.contentUrl) {
          let result = await this.fetchEmailContent(copyEmail.contentUrl)
          copyEmail.content = result;
        }else {
          copyEmail.content = ''
        }
      }
      this.$refs.email.openEmail(copyEmail, this.emailType);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async moveEmail() {
      this.moveForm.uids = this.multipleSelection.map(item => item.messageUid);
      if(!await this.$httpN.postB('crm/mail/message/move', this.moveForm, false)) return;
      formUtil.submitSuccess('移动成功');
      this.moveDialogVisible = false;
      this.getListData(true)
      this.emailDetail = {};
    },
    async openMoveDialog() {
      if(this.moveToList.length === 0) {
        let result = await this.$httpN.get('crm/mail/folder/tree');
        result.forEach((item) => {
          if(item.sysFolderName !== '草稿箱' && item.sysFolderName !== '待处理') this.moveToList.push(item);
        })
      }
      this.moveForm.sourceFolderId = this.folderId;
      this.moveForm.targetFolderId = this.folderId;
      this.moveDialogVisible = true;
    },
    async editEmail() {
      let emailDetail = await this.$httpN.postQ('crm/mail/message/info', {messageId: this.multipleSelection[0].id});
      let copyEmail = formUtil.deepCopy(emailDetail);
      this.$refs.email.openEmail(copyEmail, 'cg');
    },
    refreshEmail() {
      formUtil.submitConfirm('您确定要刷新邮箱吗？', async ()=> {
        if(!await this.$httpN.postQ('crm/mail/account/refresh',{accountId: ''}, false)) return;
        this.$parent.refreshEmail();
        this.searchItem(true)
      })
    },
    dealEmail(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要设置为已处理吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/message/deal', ids, false)) return;
        formUtil.submitSuccess('处理成功');
        this.getListData(true)
      })
    },
    redealEmail(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要设置为未处理吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/message/undeal', ids, false)) return;
        formUtil.submitSuccess('处理成功');
        this.getListData(true)
      })
    },
    delEmail(id) {
      if(this.emailType === 'hsz') return this.forceDelEmail(id);
      let ids = id ? [id]: this.multipleSelection.map(item => item.messageUid);
      formUtil.submitConfirm('您确定要删除邮件吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/message/delete2Trash', {uids: ids, sourceFolderId: this.folderId}, false)) return;
        formUtil.submitSuccess('删除成功');
        this.getListData(true)
        this.emailDetail = {};
      })
    },
    delDsTask(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要删除定时任务吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/messageTimer/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.getListData(true)
        this.emailDetail = {};
      })
    },
    rebackEmail(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.messageUid);
      formUtil.submitConfirm('您确定要恢复邮件吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/message/restore', {uids: ids}, false)) return;
        formUtil.submitSuccess('恢复成功');
        this.getListData(true)
        this.emailDetail = {};
      })
    },
    forceDelEmail(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.messageUid);
      formUtil.submitConfirm('您确定要彻底删除邮件吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/message/delete', {uids: ids}, false)) return;
        formUtil.submitSuccess('删除成功');
        this.getListData(true)
        this.emailDetail = {};
      })
    },
    async getEmailDetail(email) {
      if(this.emailType === 'ds') {
        this.emailDetail = email;
      }else {
        this.emailDetail = await this.$httpN.postQ('crm/mail/message/info', {messageId: email.id});
        if(!this.emailDetail.content) {
          if(this.emailDetail.contentUrl) {
            let result = await this.fetchEmailContent(this.emailDetail.contentUrl)
            this.emailDetail.content = result;
          }else {
            this.emailDetail.content = ''
          }
        }
      }
      this.$refs.iframewrapper.scrollTop = 0;
      this.$nextTick(() => {
        let iframe = this.$refs.emailiframe;
        let iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        iframe.height = 150;
        setTimeout(() => {
          iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
        }, 100)
      })
    },
    async remoteMethod(query) {
      if (query !== '' && query.length >= 2) {
        this.loading = true;
        this.custormerList = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: query, accountId: ''}, false);
        this.loading = false;
      } else {
        this.custormerList = [];
      }
    },
    openEmailDialog() {
      let addressorStr = this.multipleSelection.map(item => item.addressor).join(',');
      this.$refs.email.openEmail({receive: addressorStr}, '');
    },
    resetFilter() {
      this.filterData = {
        receive: '',
        addressor: '',
        isDeal: ''
      };
      this.timeRange = ['', ''];
    },
    resetTimeFilter() {
      this.filterData2 = {
        sendType: '',
        sendResult: '',
        hasSent: '',
        subject: ''
      };
    },
    changeCustomer(val) {
      this.custormerList.forEach((item) => {
        if(item.id === val) {
          this.filterData.customerNo = item.code;
        };
      })
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.getListData(true)
    },
    currentChangeHandle(page) {
      this.page = page;
      this.getListData()
    },
    openInitEmailDialog() {
      this.showEmailInit = true;
    },
    previewPic(url) {
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) return this.dingPreviewPic(url);
    },
    canPreview(url) {
      return /\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url);
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(!url) return;
      var x = new XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = 'blob';
      x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
      }
      x.send();
    },
    fetchEmailContent(url) {
      let promise = new Promise((resolve) => {
        let encodeUrl = url.replace('https://livolo-office.oss-cn-hangzhou.aliyuncs.com/mailContent/', '');
        let newUrl = 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/mailContent/' + encodeURIComponent(encodeUrl);
        var x = new XMLHttpRequest();
        x.open("GET", newUrl, true);
        x.responseType = 'html';
        x.onload=function(e) {
          resolve(x.response)
        }
        x.send();
      })

      return promise
    },
    getListData(init) {
      if(this.emailType === 'ds') {
        this.searchTimeItem(init);
      }else{
        this.searchItem(init);
      }
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/mail/message/list',{
        limit: this.pageSize,
        isDeal: this.folderId === '-1' ? false: this.filterData.isDeal,
        receive: this.filterData.receive,
        addressor: this.filterData.addressor,
        dateBegin: this.timeRange[0]? this.timeRange[0] + ' 00:00:00' : '',
        dateEnd: this.timeRange[1]? this.timeRange[1] + ' 23:59:59': '',
        page: this.page,
        folderId: this.folderId
      })
      if(data === '请先创建邮箱账号') return this.openInitEmailDialog();
      this.tableData = data.list;
      this.totalPage = data.totalCount
    },
    async searchTimeItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/mail/messageTimer/list',{
        limit: this.pageSize,
        sendType: this.filterData2.sendType,
        sendResult: this.filterData2.sendResult,
        hasSent: this.filterData2.hasSent,
        subject: this.filterData2.subject,
        page: this.page,
      })
      this.tableData = data.list;
      this.totalPage = data.totalCount
    },
    async initEmail() {
      if(!await this.$httpN.postB('crm/mail/account/save', this.emailForm)) return;
      formUtil.submitSuccess('成功');
      this.showEmailInit = false;
      this.getListData(true)
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    async sendEmail() {
      let receiveArr = this.emailDetail.receive.match(/(?!<)([^<>])+(?=>)/g) || [];
      let ccArr = this.emailDetail.cc.match(/(?!<)([^<>])+(?=>)/g) || [];
      var formData = new FormData();
      formData.append("accountId", this.emailDetail.accountId);
      formData.append("messageId", this.emailDetail.id);
      formData.append("receive", receiveArr.join(';'));
      formData.append("cc", ccArr.join(';'));
      formData.append("content", this.emailDetail.content);
      formData.append("subject", this.emailDetail.subject);
      formData.append("fromDraft", true);
      if(!await this.$httpN.uploadNew('crm/mail/message/transmit', formData)) return;
      formUtil.submitSuccess('发送成功');
      let loadingControl = Loading.service({fullscreen: true,background: 'rgba(0, 0, 0, 0.7)',text: '加载中...'});
      setTimeout(() => {
        this.getListData(true)
        loadingControl.close();
        this.emailDetail = {};
      }, 2500);
    }
  }
}
</script>

<style lang="scss" scoped>
  .header{
    position: relative;
    padding: 10px 0 0 20px ;
    .filter{
      cursor: pointer;
      float: right;
      margin-right: 30px;
      line-height: 30px;
      img{
        width: 16px;
        margin-right: 3px;
      }
    }
    .mask{
      position: fixed;
      height: 100vh;
      width: 100%;
      top: 0;
      right: 0;
      z-index: 3;
    }
    .filter-wrapper{
      position: absolute;
      width: 455px;
      padding-bottom: 20px;
      background: white;
      top: 48px;
      right: 20px;
      z-index: 99;
      border-radius: 5px;
      box-shadow: 0 0 3px black;
      .filter-header{
        line-height: 40px;
        padding-left: 16px;
        border-bottom: 1px solid #DDD;
        margin-bottom: 20px;
      }
      .filter-arrow{
        width:12px;
        height:12px;
        position: absolute;
        top: -7px;
        right: 20px;
        box-shadow: 0 0 3px black;
        transform: rotate(45deg);
      }
      .filter-white{
        width:18px;
        height:18px;
        position: absolute;
        top: -2px;
        right: 17px;
        border-radius: 3px;
        background: white;
      }
    }
  }
  .data-wrapper{
    padding: 0 20px;
    margin-top: 10px;
  }
  .email-wrapper{
    margin-top: 10px;
    height: calc((100vh - 122px) / 2);
    background-color: #f4f6f9;
    padding: 12px;
    .email-detail{
      box-shadow: 0 0 1px 0 rgba(0,0,0,.12), 0 1px 4px 0 rgba(0,0,0,.26);
      background-color: #fff;
      border-radius: 4px;
      border: 1px solid rgba(0,0,0,.06);
      height: 100%;
      overflow: auto;
      padding: 20px;
      .email-header{
        position: relative;
        p{
          margin: 0 0 5px;
          font-size: 12px;
          color: #7F7F7F;
        }
        .title{
          font-size: 18px;
          font-weight: bold;
          color: black;
          margin-bottom: 10px;
        }
        .email-btns{
          position: absolute;
          top: 0;
          right:0;
        }
      }
      .cutline{
        margin: 15px  0;
        width: 100%;
        border-top: 1px solid rgba(0,0,0,.06);
      }
      .email-file{
        display: flex;
        margin-top: 20px;
        .email-file-wrapper{
          .file{
            float:left;
            display: flex;
            width: 268px;
            height: 56px;
            background: #efefef;
            border-radius: 2px;
            margin-right: 16px;
            margin-bottom: 5px;
            &:hover{
              .file-info .file-action{
                visibility: visible;
              }
            }
            .file-type{
              width: 56px;
              text-align: center;
              line-height: 56px;
              img{
                width: 32px;
                height: 32px;
                text-align: center;
              }
            }
            .file-info{
              position: relative;
              width: calc(100% - 56px);
              p{
                margin: 0;
                font-size: 12px;
                line-height: 16px;
              }
              >p:first-child{
                margin-top: 12px;
                color:black;
              }
              >p:last-child{
                color: #6f7072;
              }
              .file-action{
                position: absolute;
                width: 100%;
                height: 100%;
                top: 0;
                left: 0;
                visibility: hidden;
                background-color: #efefef;
                opacity: .9;
                filter: alpha(opacity=90);
                padding: 11px;
                text-align: right;
                line-height: 34px;
                i{
                  font-size: 20px;
                  margin-right: 5px;
                  padding: 5px;
                  cursor: pointer;
                  &:hover{
                    background-color: rgba(0,0,0,.08);
                    color: #444547;
                  }
                }
              }
            }
          }
        }
      }
    }
    .emial-empty{
      border-radius: 4px;
      border: 1px dashed black;
      height: 100%;
      padding: 20px;
      text-align: center;
      color: black;
      font-size: 16px;
      display: flex;
      justify-content:center;
      align-items: center;
    }
  }
  .select-btn{
    display: inline-block;
    font-weight: normal;
    margin-right: 5px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    position: relative;
    cursor: pointer;
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
  .fileitem{
    cursor: pointer;
    line-height: 32px;
    margin-bottom: 5px;
    background: #F5F5F5;
    width: 474px;
    padding-left:15px;
    font-size: 12px;
    .uploadtip{
      float:right;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .addfilebtn{
    cursor: pointer;
    color: #909399;
    display: block;
    font-weight: normal;
  }
</style>